<?php
error_reporting(E_ALL ^ E_NOTICE);
header('Access-Control-Allow-Origin: *');
header("Content-type:text/html;charset=utf-8");
date_default_timezone_set("Asia/Shanghai");
define('HTTP_ROOT', str_replace('\\', '/', realpath(dirname(__FILE__))));
include "upload.class.php";

function writeLog($content) {
    static $head = 1;

    $logFile = './logs/'.date('Ym/d').'.log';
    if($head) {
        file_rput_contents($logFile, date('[Y-m-d H:i:s] ').$_SERVER['REQUEST_URI'], FILE_APPEND);
        $head = 0;
    }

    file_rput_contents($logFile, $content, FILE_APPEND);
}

function file_rput_contents($file, $content, $flags = 0, $context = null) {
    $dir = dirname($file);
    is_dir($dir) or mkdir($dir, 0777, true);

    $content = (is_array($content) ? var_export($content, true) : $content)."\r\n";
    file_put_contents($file, $content, $flags, $context);
}

writeLog($_POST);
writeLog($_FILES);

$up = new fileupload();
//设置属性（上传的位置、大小、类型、设置文件名是否要随机生成）
$path = "./upload/".date('Ymd/');
$newFileName = '';
if(isset($_POST['path']) && $_POST['path']) {
    $path = './'.ltrim(dirname($_POST['path']), '/');
    $newFileName = basename($_POST['path']);
    $up->set("newFileName", $newFileName);
}
$up->set("path", $path);
$up->set("maxsize",10000000); //kb
$up->set("allowtype", 'all');//可以是"doc"、"docx"、"xls"、"xlsx"、"csv"和"txt"等文件，注意设置其文件大小
$up->set("israndname",true);//true:由系统命名；false：保留原文件名

//使用对象中的upload方法，上传文件，方法需要传一个上传表单的名字name：pic
//如果成功返回true，失败返回false

header('Content-type: application/json');

if($up->upload("Filedata")){
    //获取上传成功后文件名字
    $result = array(
        'status' => 1,
        'url' => $up->getNewFileUrl()
    );
}else{
    //获取上传失败后的错误提示
    $result = array(
        'status' => 0,
        'msg' => $up->getErrorMsg()
    );
}

writeLog('Result:');
writeLog($result);

echo json_encode($result);